<template>

  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="postName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="阶段名称" prop="stageName">
        <el-input
          v-model="queryParams.stageName"
          placeholder="请输入阶段名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:paper:add']"
        >新增试卷</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:post:edit']"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:post:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷编号" align="center" prop="paperId" />
      <el-table-column label="试卷名称" align="center" prop="paperName" />
      <el-table-column label="阶段名称" align="center" prop="stageName" />
      <el-table-column label="考试时间" align="center" prop="totalTime"/>
      <el-table-column label="考试总分" align="center" prop="totalMark"/>
      <el-table-column label="及格线" align="center" prop="passMark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showExam(scope.row)"
            v-hasPermi="['store:paper:show']"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="echartsCount(scope.row)"
            v-hasPermi="['store:paper:echart']"
          >统计详情</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['store:paper:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-row :gutter="15">
      <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px"
               label-position="left">
        <el-col :span="13">
          <el-form-item label="试卷名称" prop="paperName">
            <el-input v-model="form.paperName" placeholder="请输入试卷名称" :maxlength="11" show-word-limit
                      clearable prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="选择题库" prop="stores" >
            <el-select v-model="form.storeId" placeholder="请选择题库" @change="showCounts"
                       :style="{width: '100%'}">
              <el-option   v-for="item in storeOptions"
                           :key="item.storeId"
                           :label="item.storeName"
                           :value="item.storeId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  v-if="showCounts" label="题目数量" style="color: #00afff"> {{ allCounts }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="题目数量" prop="singleCount">
            <el-input-number v-model.number="form.singleCount" placeholder="题目数量"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试时间" prop="totalTime">
            <el-input-number v-model.number="form.totalTime" placeholder="考试时间"></el-input-number>
          </el-form-item>
        </el-col>
      </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listPaper, getPaper, delQues, addPaper, updateQues, getStoreCount, delPaper} from "@/api/store/paper";
import {delStage, getStage} from "@/api/stage/stagelist";
import axios from "axios";
import {listDetail, listStuDetail} from "@/api/store/detail";

export default {
  name: "Ques",
  dicts: ['sys_normal_disable'],
  data() {
    const validatePass = (rule, value, callback) => {
      if (value > this.allCounts) {
        callback(new Error('题库数量不够'));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //试卷Id
      paperId:undefined,
      paperName:undefined,
      totalTime:undefined,
      totalMark:undefined,
      passMark:undefined,
      singleCount:0,
      totalScore:undefined,
      storeOptions:[],
      storeName:undefined,
      storeId:undefined,
      allCounts:undefined,
      status:"未完成",
      stuList:[],
      userList:[],

      // 总条数
      total: 0,
      // 岗位表格数据
      paperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paperId:undefined,
        paperName:undefined,
        totalTime:undefined,
        totalMark:undefined,
        passMark:undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paperName: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" }
        ],
        totalTime: [
          { required: true, message: "时间不能为空", trigger: "blur" }
        ],
        singleCount:[
          {
            required:true,message: "必须填写题目数量", trigger: "blur"
          },
          { validator: validatePass, trigger: 'blur' }


        ]
      }
    };
  },
  created() {
    this.getList();
  },

  computed: {
    addtotal() {
      return 100;
    },
  },


  methods: {
    /**开始考试*/
    startExam(row){
      listDetail().then((res)=>{
        this.stuList = res.rows;
        listStuDetail().then((res)=>{
          this.userList = res.rows;
          for (let item of this.stuList){
            for (let item1 of this.userList){
              if (item.userId === item1.userId && row.paperId === item1.paperId){
                return  this.$message("您已完成该考试");
              }
            }
          }
          this.$router.push("/exam/"+row.paperId);

        })

      });

    },

    echartsCount(row){
      this.$router.push("/echarts/"+row.paperId)
    },
    showExam(row){
      this.$router.push("/examDetail/"+row.paperId)
    },


    /** 显示所有 */
    getList() {
      this.loading = true;
      listPaper(this.queryParams).then((response) => {
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        quesId: undefined,
        storeId:undefined,
        quesName: undefined,
        quesHard:undefined,
        quesType:undefined,
        selContA:'',
        selContB:'',
        selContC:'',
        selContD:'',
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.storeId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getPaper().then(response => {
        this.storeOptions = response.stores;
        this.singleCount = response.singleCount;
        this.judgeCount = response.judgeCount;
        this.manyCount = response.manyCount;
        this.open = true;
        this.title = "添加试卷";
      });
      this.reset();
    },

    showCounts(){
      getStoreCount(this.form.storeId).then(res=>{
        this.allCounts = res.data;
      });


    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const quesId = row.quesId || this.ids
      getQues(quesId).then(response => {
        this.storeOptions = response.stores;
        this.form = response.data;
        this.open = true;
        this.title = "修改题目";
        this.typeSelect = response.data.quesType
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.quesId != undefined) {
            updateQues(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paperIds = row.paperId || this.ids;
      this.$modal.confirm('是否确认删除试卷编号为"' + paperIds + '"的数据项？').then(function() {
        return delPaper(paperIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.diaolog .el-table .el-table__header-wrapper thead th,
.diaolog .el-table .el-table__fixed-header-wrapper thead th {
  display: none;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
